package com.jiang.jixiang.ui;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.widget.FrameLayout;

import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.jiang.jixiang.R;
import com.jiang.jixiang.api.ApiUrl;
import com.jiang.jixiang.bean.PayTypeBean;
import com.jiang.jixiang.bean.UserInfoBean;
import com.jiang.jixiang.databinding.ActivityPaytypeBinding;
import com.jiang.jixiang.network.CommonalityModel;
import com.jiang.jixiang.network.NetWorkListener;
import com.jiang.jixiang.network.okHttpModel;
import com.jiang.jixiang.tools.PubDiaUtils;
import com.jiang.jixiang.ui.adapter.PayTypeAdapter;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.AgentWebConfig;
import com.just.agentweb.WebViewClient;
import com.ws.universal.tools.base.BaseActivity;
import com.ws.universal.tools.base.ManageActivity;
import com.ws.universal.tools.eventbus.BaseBusData;
import com.ws.universal.tools.eventbus.BusCode;
import com.ws.universal.tools.eventbus.EventBusUtil;
import com.ws.universal.tools.utils.GsonUtils;
import com.ws.universal.tools.utils.LogcatUtils;
import com.ws.universal.tools.utils.StringUtils;
import com.ws.universal.tools.utils.ToastUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class PayTypeActivity extends BaseActivity implements NetWorkListener {
    private ActivityPaytypeBinding binding;
    private PayTypeAdapter payTypeAdapter;
    private PayTypeBean payTypeBean;
    private Bundle bundle;
    private String amount;

    private ActivityResultLauncher<Intent> intentActivityResultLauncher;

    @Override
    protected void initCreate(Bundle savedInstanceState) {
        ManageActivity.putActivity(this.getClass().getSimpleName(), this);
        binding = ActivityPaytypeBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        bundle = getIntent().getExtras();
        amount = bundle.getString("amount");


    }

    @Override
    protected void initView() {
        binding.inTitle.titleTextTv.setText(R.string.select_pay_method);
        binding.inTitle.titleLeftBtn.setOnClickListener(view -> {
            onBackPressed();
        });
        binding.tvAmount.setText(StringUtils.getString(getString(R.string.money), amount));

        payTypeAdapter = new PayTypeAdapter();
        LinearLayoutManager manager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }

            @Override
            public boolean canScrollHorizontally() {
                return false;
            }
        };
        binding.rcyData.setLayoutManager(manager);
        binding.rcyData.setAdapter(payTypeAdapter);


        payTypeAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                indexPosition = position;
                toggleSelection();

            }
        });


        showProgressDialog(false);
        loadData();

        /*binding.rlSelectBank.setOnClickListener(view -> {
            if (NoDoubleClickUtils.isDoubleClick()) {
                Intent intent = new Intent(this, SelectBankActivity.class);
                intentActivityResultLauncher.launch(intent);
            }

        });

        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result.getData() != null && result.getResultCode() == Activity.RESULT_OK) {
                    String bankName = result.getData().getStringExtra("bankName");
                    binding.selectBankParams.setText(bankName);
                    selectBankParams = result.getData().getStringExtra("selectBankParams");

                }
            }

        });*/

        binding.btnSubmit.setChangeAlphaWhenPress(true);
        binding.btnSubmit.setOnClickListener(v -> {
            showProgressDialog(false);
            recharge(amount);
        });
    }


    private void loadUserInfo() {
        Map<String, String> params = new HashMap<>();
        okHttpModel.post(ApiUrl.getUserInfo_Api, params, ApiUrl.getUserInfo_Api_ID, this);
    }


    private void loadData() {
        Map<String, String> params = new HashMap<>();
        okHttpModel.post(ApiUrl.recharge_Api, params, ApiUrl.recharge_Api_ID, this);
    }

    private int indexPosition;

    private void toggleSelection() {
        //单选
        for (int i = 0; i < payTypeAdapter.getData().size(); i++) {
            if (i == indexPosition) {
                payTypeAdapter.getData().get(indexPosition).setChoose(true);
            } else {
                payTypeAdapter.getData().get(i).setChoose(false);
            }
        }

        payTypeAdapter.notifyDataSetChanged();
    }


    private void recharge(String amount) {
        Map<String, Object> params = new HashMap<>();
        params.put("amount", amount);
        params.put("pay_type", payTypeAdapter.getData().get(indexPosition).getValue());
        okHttpModel.postJson(ApiUrl.recharge_Api, params, ApiUrl.recharge_Api_ID, this);

    }


    @Override
    public void onSucceed(JSONObject jsonData, int id, CommonalityModel commonality) {

        JSONObject data = jsonData.optJSONObject("data");
        switch (id) {
            case ApiUrl.getUserInfo_Api_ID:
                stopProgressDialog();


                UserInfoBean userInfoBean = GsonUtils.parseJObject(data.toString(), UserInfoBean.class);
                PubDiaUtils.getInstance().saveUserInfo(data.toString());


                break;
         /*   case ApiUrl.paymentType_Api_ID:
                stopProgressDialog();
                payTypeBean = GsonUtils.parseJObject(jsonData.toString(), PayTypeBean.class);
                if (payTypeBean != null) {
                    payTypeAdapter.setList(payTypeBean.getData());
                    payTypeAdapter.setChoosed(0);


                }
                break;*/

            case ApiUrl.recharge_Api_ID:
                stopProgressDialog();
                String order_id = data.optString("id");
                String amount = data.optString("amount");
                String order_amount = data.optString("client_secret");
                String pay_url = data.optString("pay_url");
               /* if (payTypeAdapter.getData().get(indexPosition).getValue().equals("wechatpay")) {
                    WxPayBean wxPayBean = GsonUtils.parseJObject(jsonData, WxPayBean.class);
                    if (wxPayBean != null) {
                        PayReq req = new PayReq();
                        req.appId = wxPayBean.data.pay_params.appid;
                        req.partnerId = wxPayBean.data.pay_params.partnerid;
                        req.prepayId = wxPayBean.data.pay_params.prepayid;
                        req.packageValue = wxPayBean.data.pay_params.package_value;
                        req.nonceStr = wxPayBean.data.pay_params.noncestr;
                        req.timeStamp = wxPayBean.data.pay_params.timestamp;
                        req.sign = wxPayBean.data.pay_params.sign;
                        ShareHelper.mWechatApi.sendReq(req);
                        //BaseBusData baseBusData = new BaseBusData(BusCode.top_Up_Deposit, order_id);
                        //EventBusUtil.postEvent(baseBusData);
                        finish();
                    }
                } else if (payTypeAdapter.getData().get(indexPosition).getValue().equals("StripePay")) {

                }*/
                LogcatUtils.e(" pay_url 充值接口 请求成功");
                initAutoDialog(pay_url, order_id);

                break;


        }
    }

    @Override
    public void onFail(JSONObject jsonData, int id, CommonalityModel commonality) {
        stopProgressDialog();
        ToastUtils.showShort(commonality.getMessage());
    }

    @Override
    public void onError(int id, Exception e) {
        stopProgressDialog();
        ToastUtils.showShort(e.getMessage());
    }


    @Override
    public void onBackPressed() {
        if (binding.webAuto.getVisibility() == View.VISIBLE) {
            binding.webAuto.setVisibility(View.GONE);
        } else {
            super.onBackPressed();
        }


    }

    private void initAutoDialog(String loadH5Url, String order_id) {
        binding.webAuto.setVisibility(View.VISIBLE);
        AgentWeb mAgentWeb = AgentWeb.with(this).setAgentWebParent(binding.webAuto, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
                .closeIndicator().setWebViewClient(new WebViewClient() {
                    @Override
                    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                        LogcatUtils.e(" initAutoDialog " + request.getUrl().toString());
                        LogcatUtils.e(" initAutoDialog " + request.getMethod().toString());
                        BaseBusData baseBusData = new BaseBusData(BusCode.top_Up_Deposit, order_id);
                        EventBusUtil.postEvent(baseBusData);


                        return super.shouldOverrideUrlLoading(view, request);
                    }
                }).createAgentWeb().ready().go(loadH5Url);
        LogcatUtils.e(" 加载 支付链接 " + loadH5Url);
        AgentWebConfig.clearDiskCache(this.getContext());


        /*WebSettings webSettings = binding.webAuto.getSettings();
        //设置WebView属性，能够执行Javascript脚本
        webSettings.setJavaScriptEnabled(true);
        //设置可以访问文件
        webSettings.setAllowFileAccess(true);
        //内容自适应
        webSettings.setLoadWithOverviewMode(true);
        //设置支持缩放
        //        webSettings.setBuiltInZoomControls(true);
        //加载需要显示的网页
        binding.webAuto.loadUrl(loadH5Url);
        binding.webAuto.setWebViewClient(new android.webkit.WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                stopProgressDialog();

            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                view.loadUrl(url);
                return true;
            }
        });


        //适配5.0不允许http和https混合使用情况
        webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);

        //关闭硬件加速 避免个别机型不支持报错
        webSettings.setBlockNetworkImage(false);
        //关闭缓存
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        //关闭硬件加速 避免个别机型不支持报错
        webSettings.setBlockNetworkImage(false);*/
    }


    @Override
    protected void FinishDesTroy() {
        ManageActivity.removeActivity(this.getClass().getSimpleName());
    }
}
